package com.xyauto.theme.utils

import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Matrix
import android.graphics.Paint
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation
import com.bumptech.glide.load.resource.bitmap.TransformationUtils
import java.security.MessageDigest

/**
 * created by gongziyi on 2024/6/21 10:59
 */
class CenterMin : BitmapTransformation() {
    companion object {
        private const val ID = "com.xyauto.theme.utils.CenterMin"
        private val ID_BYTES = ID.toByteArray(CHARSET)
    }

    private val mPaint = Paint(Paint.DITHER_FLAG or Paint.FILTER_BITMAP_FLAG)

    override fun updateDiskCacheKey(messageDigest: MessageDigest) {
        messageDigest.update(ID_BYTES)
    }

    override fun transform(pool: BitmapPool, inBitmap: Bitmap, width: Int, height: Int): Bitmap {
        val mWidth = inBitmap.width
        val mHeight = inBitmap.height
        return if (mWidth == width && mHeight == height) {
            inBitmap
        } else {
            val outScale = width * 1f / height
            val inScale = mWidth * 1f / mHeight

            val scale: Float
            val dx: Float
            val dy: Float
            val m = Matrix()

            if (outScale > inScale) {
                scale = width * 1f / mWidth
                dx = 0f
                dy = (height - mHeight * scale) * 0.5f
            } else {
                scale = height * 1f / mHeight
                dx = (width - mWidth * scale) * 0.5f
                dy = 0f
            }
            m.setScale(scale, scale)
            m.postTranslate((dx + 0.5f).toInt().toFloat(), (dy + 0.5f).toInt().toFloat())

            val result = pool.get(width, height, getNonNullConfig(inBitmap))
            TransformationUtils.setAlpha(inBitmap, result)

            applyMatrix(inBitmap, result, m)
            return inBitmap
        }
    }

    private fun applyMatrix(inBitmap: Bitmap, targetBitmap: Bitmap, matrix: Matrix) {
        val canvas = Canvas(targetBitmap)
        canvas.drawBitmap(inBitmap, matrix, mPaint)
        canvas.setBitmap(null)
    }

    private fun getNonNullConfig(bitmap: Bitmap): Bitmap.Config = if (bitmap.config != null) bitmap.config else Bitmap.Config.ARGB_8888
}